import requests

from my_config import LOGIN_APP_MAP, LOGIN_APP_URL


def get_warrant_url(broker) -> str:
    return f"{LOGIN_APP_URL[broker]['warrant']}client_id={LOGIN_APP_MAP[broker]['client_id']}" \
           f"&redirect_uri={LOGIN_APP_MAP[broker]['redirect_uri']}"


def get_token_by_code(broker, code) -> tuple:
    params = f'code={code}'
    for k, v in LOGIN_APP_MAP[broker].items():
        params += f"&{k}={v}"
    weibo_api = f"{LOGIN_APP_URL[broker]['access_token']}{params}"

    ret = requests.post(weibo_api, headers={'Accept': 'application/json'})
    data = ret.json()
    access_token = data.get('access_token')

    if broker == 'github':
        token_type = data.get('token_type')
        user_data = requests.get(LOGIN_APP_URL[broker]['user_info'],
                                 headers={'Authorization': f'{token_type} {access_token}'}).json()
        uid = user_data.get('id')
    else:
        uid = data.get('uid')
    return access_token, uid